package xdsysadmin2

import initConfig.SysInitData
import sysUtil.JwtToken
import sysUtil.ResultCode
import sysUtil.ResultJson

class AuthFilterFilters {

    def cookieService
    def filters = {

        def result = ResultJson.resultJson()

        "/"(controller: '*', action: '*') {
            before = {
                //println "token:${request.getCookies()}"
                response.setHeader("Access-Control-Allow-Origin", "*");

                if(!SysInitData.WEB_REAL_PATH){//获取项目发布路径
                    SysInitData.WEB_REAL_PATH =  grailsApplication.getMainContext().servletContext.getRealPath("")
                }
                if(controllerName.indexOf("special") != -1){
                    return  true
                }else if(["logoff","login"].contains(actionName)){
                    return  true
                } else  {

                    def token = cookieService.getCookie("token") ?:params?.token
                    def user  = JwtToken.verifyUserByToken(token)
                    if(user){
                        params.put(JwtToken.USER_NO,user.get(JwtToken.USER_NO))
                        params.put("updater",user.get(JwtToken.USER_NO))
                        //刷新token
                        def newToken = JwtToken.create(user.userNo,user.userName)
                        def cookiePath = grailsApplication.getMainContext().servletContext.getContextPath()
                        cookieService.setCookie("token",newToken,null,cookiePath)
                    }else{
                        result.put(ResultJson.CODE.name,ResultCode.TOKEN_INVALID.code)
                        result.put(ResultJson.MESSAGE.name,ResultCode.TOKEN_INVALID.message)
                        result.put(ResultJson.MSG.name,ResultCode.TOKEN_INVALID.message)
                        //result.put(ResultJson.DATA.name,"")
                        render result.toString()
                        //println result
                        return false
                    }
                    return true
                }
            }
            after = { Map model ->

            }
            afterView = { Exception e ->

            }
        }
    }
}
